import { Request, Response, NextFunction } from "express";

interface Params {
	message: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const params = request.query as unknown as Params;
		response.setHeader("Content-Type", "text/event-stream");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Connection", "keep-alive");
		response.on("close", () => {
			response.end();
		});
		fetch("https://dashscope.aliyuncs.com/api/v1/apps/7d3f70ffb4f54cd4bedad08f30f8d25e/completion", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				Authorization: "Bearer sk-4b1d65cc4ee64f3e80983f0a5c54aedb",
				"X-DashScope-SSE": "enable",
			},
			body: JSON.stringify({
				input: {
					prompt: params.message,
				},
			}),
		}).then(async (res) => {
			const reader = res.body!.getReader();
			while (1) {
				const { done, value } = await reader.read();
				if (done) {
					console.log("done");
					response.end();
					break;
				}
				response.write(value);
			}
		});
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
